import globalCache from '../../cache.js'
import request from '../../util/request.js'

const getToken = (params) => {
  
  return new Promise((resolve, reject) => { 
    if (!params?.appid || !params?.secret) {
      reject(new Error('error access_token params'))
      return
    }  
    const payload = {
      grant_type: 'client_credential',
      appid: params.appid,
      secret: params.secret,
      force_refresh: true
    }
    const token_cache = globalCache.getCache('applet','access_token')|| undefined 
    // if (token_cache) {
    //   resolve(token_cache)
    //   return
    // }
    request.post(`https://api.weixin.qq.com/cgi-bin/stable_token`,payload)
    .then((result) => {
      if (result.errcode) {
        reject(result.errmsg)
      } else {
        globalCache.setCache('applet','access_token',result,result.expires_in * 1000)
        resolve(result)
      }
    }).catch((err) => {
      reject(err)
    });
   })

}

export default getToken